package com.lvmama.rhino.service.impl.comment;

import com.lvmama.rhino.mapperComment.CommentOverviewMapper;
import com.lvmama.rhino.pojo.comment.Enum.EnumForComment;
import com.lvmama.rhino.pojo.comment.entity.*;
import com.lvmama.rhino.pojo.comment.query.CommentBaseQuery;
import com.lvmama.rhino.pojo.comment.query.CommentStatisticsQuery;
import com.lvmama.rhino.pojo.comment.query.CommentTendencyQuery;
import com.lvmama.rhino.pojo.comment.query.ProductCommentTypeRankQuery;
import com.lvmama.rhino.pojo.comment.response.CommentOccupancyResponse;
import com.lvmama.rhino.pojo.comment.response.ProductCommentTypeRankResponse;
import com.lvmama.rhino.service.comment.CommentOverviewService;
import com.lvmama.rhino.utils.Constants;
import com.lvmama.rhino.utils.DateUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @Author:caoyong
 * @Description: 评论概述实现
 * @Date：2017/9/18
 */
@Service("commentOverviewService")
public class CommentOverviewServiceImpl implements CommentOverviewService {

    private Logger log = Logger.getLogger(CommentOverviewServiceImpl.class);
    @Autowired
    private CommentOverviewMapper commentOverviewMapper;

    /**
     * 查询点评趋势
     *
     * @param query 查询条件
     * @return 结果集
     */
    @Override
    public List<CommentTendency> selectCommentTendency(CommentTendencyQuery query) {
        log.info("selectCommentTendency start.");
        List<CommentTendency> result = null;
        try {
            result = commentOverviewMapper.selectCommentTendency(query);
            if (null == result || result.size() < 1) {
                return result;
            }
            //表示查询全部，默认查询1年内的
            if (null == query.getDays() && null == query.getStartTime()) {
                query.setDays(365);
            }
            //查询出来最近天数的数组
            String[] latestDays = null;
            if (query.getDays() != null && query.getDays() > 0) {
                latestDays = DateUtil.getLatestDays(query.getDays(), Constants.ASC);
            }
            if (null != query.getStartTime() && null != query.getEndTime()) {
                List<String> betweenDates = DateUtil.getBetweenDates(query.getStartTime(), query.getEndTime(), DateUtil.PATTERN_yyyy_MM_dd);
                String[] dates = new String[betweenDates.size()];
                latestDays = betweenDates.toArray(dates);
            }
            if (null != latestDays && latestDays.length > 0) {
                for (String day : latestDays) {
                    //好评
                    CommentTendency positive = new CommentTendency();
                    positive.setMonth(day);
                    positive.setType(EnumForComment.positive.getShowName());
                    if (!result.contains(positive)) {
                        positive.setRate(0F);
                        result.add(positive);
                    }
                    //中评
                    CommentTendency moderate = new CommentTendency();
                    moderate.setMonth(day);
                    moderate.setType(EnumForComment.neuter.getShowName());
                    if (!result.contains(moderate)) {
                        moderate.setRate(0F);
                        result.add(moderate);
                    }
                    //差评
                    CommentTendency negative = new CommentTendency();
                    negative.setMonth(day);
                    negative.setType(EnumForComment.negative.getShowName());
                    if (!result.contains(negative)) {
                        negative.setRate(0F);
                        result.add(negative);
                    }
                }
            }
        } catch (Exception e) {
            log.error("selectCommentTendency error:" + e.getMessage(), e);
        }
        log.info("selectCommentTendency end.");
        return result;
    }

    /**
     * 评论统计
     *
     * @param query 查询条件
     * @return 结果集
     */
    @Override
    public List<CommentOccupancyResponse> selectCommentStatistics(CommentStatisticsQuery query) {
        log.info("selectCommentStatistics start. query:" + query);
        List<CommentOccupancyResponse> result = new ArrayList<>();
        try {
            List<CommentStatistics> commentStatistics = commentOverviewMapper.selectCommentStatistics(query);
            if (CollectionUtils.isEmpty(commentStatistics) || (commentStatistics.size() == 1 &&
                    (commentStatistics.get(0).getCount() == 0 || StringUtils.isBlank(commentStatistics.get(0).getType())))) {
                return result;
            }
            outer:
            for (EnumForComment comment : EnumForComment.values()) {
                if (-1 == comment.getValue()) continue;
                for (CommentStatistics statistic : commentStatistics) {
                    if (comment.getShowName().equals(statistic.getType())) {
                        statistic.setCommentType(comment.getValue());
                        continue outer;
                    }
                }
                CommentStatistics sta = new CommentStatistics();
                sta.setCount(0);
                sta.setRate(0F);
                sta.setCommentType(comment.getValue());
                sta.setType(comment.getShowName());
                commentStatistics.add(sta);
            }
            Collections.sort(commentStatistics, new Comparator<CommentStatistics>() {
                @Override
                public int compare(CommentStatistics o1, CommentStatistics o2) {
                    return o2.getCommentType().compareTo(o1.getCommentType());
                }
            });

            if (!CollectionUtils.isEmpty(commentStatistics)) {
                for (CommentStatistics statistics : commentStatistics) {
                    CommentOccupancyResponse response = new CommentOccupancyResponse();
                    response.setName(statistics.getType());
                    response.setValue(statistics.getRate());
                    result.add(response);
                }
            }
        } catch (Exception e) {
            log.error("selectCommentStatistics error:" + e.getMessage());
        }
        log.info("selectCommentStatistics end.");
        return result;
    }

    /**
     * 查询点评时间分布
     *
     * @param query 查询条件
     * @return 结果集
     */
    @Override
    public List<CommentTimeDistribution> selectCommentTimeDistribution(CommentBaseQuery query) {
        log.info("selectCommentTimeDistribution start.");
        List<CommentTimeDistribution> distributions = null;
        try {
            distributions = commentOverviewMapper.selectCommentTimeDistribution(query);
        } catch (Exception e) {
            log.error("selectCommentTimeDistribution error:" + e.getMessage(), e);
        }
        log.info("selectCommentTimeDistribution end.");
        return distributions;
    }

    /**
     * 查询品类点评率占比
     *
     * @param query 查询条件
     * @return 结果集
     */
    @Override
    public List<CategoryCommentOccupancy> selectCategoryCommentOccupancy(CommentBaseQuery query) {
        log.info("selectCategoryCommentOccupancy start.");
        List<CategoryCommentOccupancy> occupancies = null;
        try {
            occupancies = commentOverviewMapper.selectCategoryCommentOccupancy(query);
        } catch (Exception e) {
            log.error("selectCategoryCommentOccupancy error:" + e.getMessage(), e);
        }
        log.info("selectCategoryCommentOccupancy end.");
        return occupancies;
    }

    /**
     * 查询产品评论类型排名
     *
     * @param query 查询条件
     * @return 结果集
     */
    @Override
    public List<ProductCommentTypeRankResponse> selectProductCommentTypeRank(ProductCommentTypeRankQuery query) {
        log.info("selectProductCommentTypeRank start.");
        List<ProductCommentTypeRankResponse> result = new ArrayList<>();
        try {
            List<ProductCommentTypeRank> typeRanks = commentOverviewMapper.selectProductCommentTypeRank(query);
            if (null != typeRanks && !typeRanks.isEmpty()) {
                int j = 1;
                for (ProductCommentTypeRank occupancy : typeRanks) {
                    ProductCommentTypeRankResponse resp = new ProductCommentTypeRankResponse();
                    String productName = occupancy.getProductName();
                    if (StringUtils.isNotBlank(productName) && Constants.UNKNOWNDATA.equals(productName.trim())) {
                        productName = "未知";
                    }
                    if (StringUtils.isBlank(productName)) {
                        productName = Constants.UNKNOWN + String.valueOf(j++);
                    } else if (Constants.UNKNOWNDATA.equals(productName.trim()) ||
                            Constants.UNKNOWNDATA2.equals(productName.trim()) ||
                            Constants.UNKNOWNDATA3.equalsIgnoreCase(productName.trim())) {
                        productName = Constants.UNKNOWN + String.valueOf(j++);
                    }
                    resp.setWorst(productName);
                    resp.setNum(occupancy.getNum());
                    result.add(resp);
                }
            }
        } catch (Exception e) {
            log.error("selectProductCommentTypeRank error:" + e.getMessage(), e);
        }
        log.info("selectProductCommentTypeRank end.");
        return result;
    }

    /**
     * 查询评论观点排名
     *
     * @param query 查询条件
     * @return 结果集
     */
    @Override
    public List<ProductCommentTypeRankResponse> selectViewpointRank(ProductCommentTypeRankQuery query) {
        log.info("selectViewpointRank start.");
        List<ProductCommentTypeRankResponse> result = new ArrayList<>();
        try {
            List<ViewpointRank> viewpointRanks = commentOverviewMapper.selectViewpointRank(query);
            if (null != viewpointRanks && !viewpointRanks.isEmpty()) {
                for (ViewpointRank viewpointRank : viewpointRanks) {
                    ProductCommentTypeRankResponse resp = new ProductCommentTypeRankResponse();
                    resp.setWorst(viewpointRank.getTags());
                    resp.setNum(viewpointRank.getNum());
                    result.add(resp);
                }
            }
        } catch (Exception e) {
            log.error("selectViewpointRank error:" + e.getMessage(), e);
        }
        log.info("selectViewpointRank end.");
        return result;
    }

    @Override
    public Integer selectAllCommentNum(CommentStatisticsQuery query) {
        return commentOverviewMapper.selectAllCommentNum(query);
    }

}
